<template>
  <a-spin :spinning='confirmLoading'>

    <j-form-container :disabled='formDisabled'>
      <a-form :form='form' slot='detail'>
        <a-row>
          <a-col :span='12'>
            <a-form-item label='合同名称' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-popup
                v-decorator="['saleName', validatorRules.saleName]"
                :trigger-change='true'
                org-fields='id,project_name,num,customer_name,bid_project_id'
                dest-fields='contractId,saleName,saleNum,customerName,bidProjectId'
                code='contract_sale_select'
                @callback='saleNamePopupCallback'
                placeholder='请选择合同'
              />
              <a-input v-decorator="['contractId']" v-show='false'></a-input>
              <a-input v-decorator="['bidProjectId']" v-show='false'></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='合同编号' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input v-decorator="['saleNum']" placeholder='请先选择合同' disabled></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='客户简称' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input v-decorator="['customerName']" placeholder='请先选择合同' disabled></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='项目经理' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-select-user-by-dep
                :multi='false'
                v-decorator="['projectCharger', validatorRules.projectCharger]"
                placeholder='请选择项目经理'
              />
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='采购简述' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input v-decorator="['summary', validatorRules.summary]" placeholder='请输入采购简述' />
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='采购总额' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input v-decorator="['purchaseTotal', validatorRules.purchaseTotal]" disabled>
                <span slot='addonAfter'>元</span></a-input
              >
            </a-form-item>
          </a-col>
          <!-- <a-col :span="12">
            <a-form-item label="交付日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date
                placeholder="请选择交付日期"
                v-decorator="['deliveryDate', validatorRules.deliveryDate]"
                :trigger-change="true"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="是否预算内" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-switch v-decorator="['withinBudget', validatorRules.withinBudget]"></j-switch>
            </a-form-item>
          </a-col> -->
          <a-col :span='12'>
            <a-form-item label='附件' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-upload v-decorator="['files', validatorRules.files]" :trigger-change='true'></j-upload>
            </a-form-item>
          </a-col>
          <a-col :span='24'>
            <a-form-item label='特殊说明' :labelCol='labelCol2' :wrapperCol='wrapperCol2'>
              <a-textarea v-decorator="['detail', validatorRules.detail]" rows='3' placeholder='请输入特殊说明' />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </j-form-container>
    <ContractSaleMoneyFlow
      :contractActualReturnMoney='contractActualReturnMoney'
      :contractActualPaymentMoney='contractActualPaymentMoney'
      :moneyFlow='+contractActualReturnMoney - +contractActualPaymentMoney'
      v-if='rowContractId'
    ></ContractSaleMoneyFlow>
    <ContractBidProjectDetailList :mainId='bidProjectId'></ContractBidProjectDetailList>
    <!-- 子表单区域 -->
    <a-tabs v-model='activeKey' @change='handleChangeTabs'>
      <a-tab-pane tab='采购明细' :key='refKeys[0]' :forceRender='true'>
        <j-editable-table
          :ref='refKeys[0]'
          :loading='ContractPurchaseApplyTable.loading'
          :columns='ContractPurchaseApplyTable.columns'
          :dataSource='ContractPurchaseApplyTable.dataSource'
          :maxHeight='300'
          :disabled='formDisabled'
          :rowNumber='true'
          :actionButton='true'
          @valueChange='tableValueChange'
        >
          <template v-slot:action='props'>
            <a
              @click='handleDelete(props)'
              :disabled='formDisabled'
              style='width: 100%; display: inherit; text-align: center'
            >
              <a-icon type='close' style='color: red; font-size: 18px'></a-icon
              >
            </a>
          </template>
          <template v-slot:remarks='props'>
            <a-popover v-if='props.text && model.id && formDisabled' :content='props.text'>
              <div>
                <a-input
                  :value='props.text'
                  :disabled='formDisabled'
                  @change='(e) => remarkInputchange(e, props)'
                ></a-input>
              </div>
            </a-popover>
            <a-input
              :value='props.text'
              :disabled='formDisabled'
              @change='(e) => remarkInputchange(e, props)'
              v-else
            ></a-input>
          </template>
        </j-editable-table>
      </a-tab-pane>
    </a-tabs>
    <a-row>
      <a-col v-if='showFlowSubmitButton' :span='24' style='text-align: center; margin-top: 20px'>
        <a-button @click='handleOk'>提 交</a-button>
      </a-col>
    </a-row>
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import { FormTypes, getRefPromise, VALIDATE_NO_PASSED, validateFormAndTables } from '@/utils/JEditableTableUtil'
import pick from 'lodash.pick'
import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
import ContractBidProjectDetailList from './ContractBidProjectDetailList'
import { toFixedTwo } from '@/utils/util'
import { randomNumber } from '@/utils/util'
import ContractSaleMoneyFlow from './ContractSaleMoneyFlow'

export default {
  name: 'ContractPurchaseApplyForm',
  mixins: [JEditableTableMixin],
  components: {
    ContractBidProjectDetailList,
    ContractSaleMoneyFlow
  },
  props: {
    //流程表单data
    formData: {
      type: Object,
      default: () => {
      },
      required: false
    },
    //表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  watch: {
    bidProjectId: {
      //选择合同后监听投标预审ID的变化，查询投标预审的数据
      handler(value) {
        if (value) {
          // getAction(this.url.queryPurchaseItemByMainId, { id: value }).then((res) => {
          //   if (res.success) {
          //     this.ContractPurchaseApplyTable.dataSource = res.result
          //   }
          // })
        }
      }
    },
    'ContractPurchaseApplyTable.dataSource': {
      //选择合同后监听投标预审ID的变化，并且将每行的总价进行计算和是否在预算内默认为是
      deep: true,
      immediate: true,
      handler(value) {
        let purchaseTotal = 0
        value.forEach((v) => {
          if (v.amount && v.unitPrice) {
            v.totalPrice = toFixedTwo(v.amount * v.unitPrice)
            purchaseTotal += +v.totalPrice
          }
          v.withinBudget = 'Y'
        })
        this.form.setFieldsValue({ purchaseTotal: toFixedTwo(purchaseTotal) })
      },
    },
    '$store.state.bpm.bpmSubmitStates': {
      immediate: true,
      handler(val) {
        if (val && val.edit && val.edit === '1') {
          this.handleOk().then(res => {
            if (res) {
              this.$store.commit('BPM_SUBMIT_STATES', { edit: '2' })
            }
          })
        }
      }
    },
    rowContractId: {
      deep: true,
      immediate: true,
      handler(value) {
        if (value) {
          this.contractSalePaymentCollection(value)
          this.queryPurchaseDetail(value)
        }
      }
    }
  },
  data() {
    return {
      model: {},
      bidProjectId: '',
      rowContractId: '',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      addDefaultRowNum: 1,
      refKeys: ['ContractPurchaseApply'],
      tableKeys: ['ContractPurchaseApply'],
      activeKey: 'ContractPurchaseApply',
      ContractPurchaseApplyTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '货物名称',
            required: true,
            key: 'goodsName',
            type: FormTypes.input,
            dictCode: 'icm_payment_collection_condition',
            placeholder: '请输入${title}',
            defaultValue: '',
            width: '20%',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '规格型号',
            required: true,
            key: 'model',
            type: FormTypes.input,
            placeholder: '请输入${title}',
            defaultValue: '',
            width: '10%',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '数量',
            required: true,
            key: 'amount',
            type: FormTypes.inputNumber,
            placeholder: '请输入${title}',
            width: '10%',
            validateRules: [
              { required: true, message: '${title}不能为空' },
              { pattern: /^[1-9]\d*$/, message: '请输入数字!' }
            ]
          },
          {
            title: '单价(元)',
            required: true,
            key: 'unitPrice',
            width: '9%',
            type: FormTypes.inputNumber,
            placeholder: '请输入单价',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '总价',
            required: false,
            disabled: true,
            key: 'totalPrice',
            width: '9%',
            type: FormTypes.inputNumber
          },
          {
            title: '是否预算内',
            required: true,
            key: 'withinBudget',
            dictCode: 'switch_status',
            width: '10%',
            type: FormTypes.select,
            placeholder: '请输入${title}',
            validateRules: [{ required: true, message: '请选择${title}' }],
            defaultValue: '是'
          },
          {
            title: '交付日期',
            required: true,
            key: 'deliveryDate',
            width: '12%',
            type: FormTypes.date,
            placeholder: '请选择',
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '备注',
            key: 'remarks',
            type: FormTypes.slot,
            slotName: 'remarks',
            placeholder: '请输入${title}',
            width: '15%'
          },
          {
            title: '操作',
            key: 'action',
            width: '5%',
            type: FormTypes.slot,
            slotName: 'action'
          }
        ]
      },
      confirmLoading: false,
      validatorRules: {
        saleName: {
          rules: [{ required: true, message: '请选择合同！' }]
        },
        summary: {
          rules: [{ required: true, message: '请输入采购简述！' }]
        },
        projectCharger: {
          rules: [{ required: true, message: '请选择项目经理！' }]
        },
        deliveryDate: {
          rules: [{ required: true, message: '请选择交付日期！' }]
        },
        withinBudget: {
          rules: [{ required: true, message: '请选择是否在预算内！' }],
          initialValue: 'Y'
        }
      },
      fields: [
        'bidProjectId',
        'projectCharger',
        'withinBudget',
        'detail',
        'deliveryDate',
        'saleName',
        'contractId',
        'saleNum',
        'customerName',
        'files',
        'summary'
      ],
      url: {
        add: '/contract/contractPurchaseApply/add',
        edit: '/contract/contractPurchaseApply/edit',
        queryById: '/contract/contractPurchaseApply/queryById',
        ContractPurchaseApplyTable: {
          list: '/contract/contractPurchaseApply/queryItemByMainId'
        },
        contractSalePaymentCollection: {
          list: '/contract/contractSale/queryContractSalePaymentCollectionByMainId'
        },
        queryPurchaseItemByMainId: '/bid/bidProject/queryPurchaseItemByMainId',
        purchaseContractList: '/contract/contractPurchase/nonPermissionList'
      },
      contractActualReturnMoney: '',
      contractActualPaymentMoney: ''
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    }
  },
  created() {
    //如果是流程中表单，则需要加载流程表单data
    this.showFlowData()
  },
  methods: {
    handleOk() {
      const that = this
      return new Promise(((resolve, reject) => {
        /** 触发表单验证 */
        this.getAllTable().then(tables => {
          /** 一次性验证主表和所有的次表 */
          return validateFormAndTables(this.form, tables)
        }).then(allValues => {
          if (typeof this.classifyIntoFormData !== 'function') {
            throw this.throwNotFunction('classifyIntoFormData')
          }
          let formData = this.classifyIntoFormData(allValues)
          // 发起请求
          let url = this.url.add, method = 'post'
          if (this.model.id) {
            url = this.url.edit
            method = 'put'
          }
          that.confirmLoading = true
          httpAction(url, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
              resolve(true)
              that.close()
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
          // return this.request(formData)
        }).catch(e => {
          this.$store.commit('BPM_SUBMIT_STATES', {})
          if (e.error === VALIDATE_NO_PASSED) {
            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
      }))

    },
    // add() {
    //   this.edit({})
    // },
    // edit(record) {
    //   this.form.resetFields()
    //   this.model = Object.assign({}, record)
    //   this.visible = true
    //   this.$nextTick(() => {
    //     this.form.setFieldsValue(pick(this.model, this.fields))
    //   })
    // },
    handleDelete(props) {
      let { rowId, target } = props
      target.removeRows(rowId)
      this.getValues()
    },
    tableValueChange({ row }) {
      if (row.amount && row.unitPrice) {
        let totalPrice = toFixedTwo(row.amount * row.unitPrice)
        this.$refs.ContractPurchaseApply.setValues([{ rowKey: row.id, values: { totalPrice } }])
        this.getValues()
      } else {
        this.form.setFieldsValue({ purchaseTotal: 0 })
      }
    },
    getValues() {
      this.$refs.ContractPurchaseApply.getValues((error, value) => {
        let count = 0
        value.forEach((v) => {
          if (v.totalPrice) {
            count += +v.totalPrice
          }
        })
        this.form.setFieldsValue({ purchaseTotal: toFixedTwo(count) })
      })
    },
    remarkInputchange(event, props) {
      this.$nextTick(() => {
        let value = event.target.value
        let values = [
          {
            rowKey: props.getValue().id,
            values: {
              remarks: value,
              goodsName: props.getValue().goodsName,
              model: props.getValue().model,
              amount: props.getValue().amount,
              unitPrice: props.getValue().unitPrice,
              totalPrice: props.getValue().totalPrice,
              deliveryDate: props.getValue().deliveryDate,
              withinBudget: props.getValue().withinBudget
            }
          }
        ]
        this.$refs.ContractPurchaseApply.setValues(values)
      })
    },
    addBefore() {
      this.form.resetFields()
      this.ContractPurchaseApplyTable.dataSource = []
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      let fieldval = pick(this.model, this.fields)
      this.$nextTick(() => {
        this.form.setFieldsValue(fieldval)
      })
      if (this.model.bidProjectId) {
        this.bidProjectId = this.model.bidProjectId
      }
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.ContractPurchaseApplyTable.list, params, this.ContractPurchaseApplyTable)
      }
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        itemList: allValues.tablesValue[0].values
      }
    },
    //渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        let params = { id: this.formData.dataId }
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.edit(res.result)
          }
        })
      }
    },
    close() {
      this.bidProjectId = null
      this.rowContractId= null
    },
    queryItemBybidProjectId(bidProjectId) {
      getAction(this.url.queryPurchaseItemByMainId, { id: bidProjectId }).then((res) => {
        if (res.success) {
          let result = res.result
          result.forEach((v) => {
            v.id = this.generateId()
          })
          this.ContractPurchaseApplyTable.dataSource = result
        }
      })
    },
    generateId() {
      let timestamp = new Date().getTime()
      return `${timestamp}${randomNumber(7)}`
    },
    contractSalePaymentCollection(id) {
      getAction(this.url.contractSalePaymentCollection.list, { id }).then((res) => {
        if (res.success) {
          this.contractActualReturnMoney = res.result[0].actualMoney
        }
      })
    },
    queryPurchaseDetail(value) {
      getAction(this.url.purchaseContractList, { saleId: value, pageNo: -1, pageSize: -1 }).then((res) => {
        if (res.success) {
          let count = 0
          res.result.records.forEach(item => {
            item.contractPurchasePaymentList.forEach(v => {
              count += v.actualMoney
            })
          })
          this.contractActualPaymentMoney = count
        }
      })
    },
    saleNamePopupCallback(row) {
      this.bidProjectId = row.bidProjectId
      this.rowContractId = row.contractId
      this.queryItemBybidProjectId(row.bidProjectId)
      this.form.setFieldsValue(pick(row, this.fields))
    },
    popupCallback(row) {
      this.form.setFieldsValue(pick(row, this.fields))
    }
  }
}
</script>